package com.yequan.designpattern.singleton.lazysingleton;

/**
 * @Auther: yq
 * @Date: 2019/1/9 14:53
 * @Description:
 */
public class HigherThreadUnsafeLazySingleton {

    /**
     * 懒汉式（线程不安全，效率提高）
     */
    private static HigherThreadUnsafeLazySingleton instance = null;

    private HigherThreadUnsafeLazySingleton() {
    }

    public static HigherThreadUnsafeLazySingleton getInstance() {
        if (null == instance) {
            try {
                Thread.sleep(300);//模仿多线程环境下耗时操作
                synchronized (HigherThreadUnsafeLazySingleton.class) {
                    instance = new HigherThreadUnsafeLazySingleton();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return instance;
    }

    public static void main(String[] args) {
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("thread1 >>>>> " + HigherThreadUnsafeLazySingleton.getInstance().hashCode());
            }
        });
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("thread2 >>>>> " + HigherThreadUnsafeLazySingleton.getInstance().hashCode());
            }
        });
        Thread thread3 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("thread3 >>>>> " + HigherThreadUnsafeLazySingleton.getInstance().hashCode());
            }
        });

        thread1.start();
        thread2.start();
        thread3.start();
    }

}
